export function createCode(): string {
  var selectChar: any[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];//所有候选组成验证码的字符，也可以用中文的
  let code = "";
  var codeLength = 4;//验证码的长度
  for (var i = 0; i < codeLength; i++) {
    var index = Math.floor(Math.random() * selectChar.length)//随机数
    code += selectChar[index];
    //$("#createCade").html(code)
  }
  sessionStorage.setItem('code', code);
  drawCode(code);
  return code
}

function drawCode(ImageCode: string) {
  var str = '';
  var canvas = document.getElementById("verifyCanvas") as HTMLCanvasElement; //获取HTML端画布"
  var context = canvas.getContext("2d"); //获取画布2D上下文
  if (context) {
    context.fillStyle = "white"; //画布填充色
    context.fillRect(0, 0, canvas.width, canvas.height); //清空画布
    context.fillStyle = "cornflowerblue"; //设置字体颜色
    context.font = "25px Arial"; //设置字体
    var rand = new Array();
    var x = new Array();
    var y = new Array();
    for (var i = 0; i < 4; i++) {
      rand.push(rand[i]);
      rand[i] = ImageCode.charAt(i);
      x[i] = i * 20 + 10;
      y[i] = Math.random() * 20 + 20;
      context.fillText(rand[i], x[i], y[i]);
    }
    str = rand.join('').toUpperCase();
    for (var i = 0; i < 30; i++) {
      drawDot(canvas, context);
    }
  }
}

// 随机点(所谓画点其实就是画1px像素的线，方法不再赘述)
function drawDot(canvas: any, context: CanvasRenderingContext2D) {
  var px = Math.floor(Math.random() * canvas.width);
  var py = Math.floor(Math.random() * canvas.height);
  context.moveTo(px, py);
  context.lineTo(px + 1, py + 1);
  context.lineWidth = 0.2;
  context.strokeStyle = getBackgroud(0.1);
  context.stroke();
}

// 生成随机背景
function getBackgroud(Transparency: number) {
  var RColor = 255 * Math.random();
  var GColor = 255 * Math.random();
  var BColor = 255 * Math.random();
  return "rgba(" + RColor + ", " + GColor + ", " + BColor + ", " + Transparency + ")";
}
